package com.qf.common.core.exception;



import com.qf.common.core.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(CustomerException.class)
    public R exceptionHandler (CustomerException e) {
        return R.fail( e.getMsg());
    }
    @ExceptionHandler(ConstraintViolationException.class)
    public R<?> valiateException(ConstraintViolationException ex) {
        String erroorInfo = "";
        // 获取对应的迭代器
        Iterator<ConstraintViolation<?>> iterator = ex.getConstraintViolations().iterator();
        while (iterator.hasNext()) {
            ConstraintViolation<?> next = iterator.next();
            // 获取异常信息
            System.out.println(next.getMessage());
            erroorInfo += next.getMessage() + ";";
        }
        log.error("参数验证失败，{}", erroorInfo);
        return R.fail(erroorInfo);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R validationException(MethodArgumentNotValidException e) {
        StringBuilder sb = new StringBuilder();
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        String message = allErrors.stream().map(s -> s.getDefaultMessage()).collect(Collectors.joining(";"));
        // 一般异常需要记录到日志系统
        log.error("参数验证失败，{}", message);
        return R.fail(message);
    }

/*    @ExceptionHandler(Exception.class)
    public R exception(Exception e) {
        log.error("全局异常: {}", e.getMessage());
        return R.fail("未知异常，请联系管理员"+e.toString());
    }*/


}
